#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

const std::string gpipeFile = "./fifo";
const mode_t gfifomode = 0600;
const int gdefault = -1;
const int gforRead = O_RDONLY;
const int gforWrite = O_WRONLY;
const int gsize = 1024;

// 模拟进程间同步的过程

class Fifo
{
private:
    // 只读打开只写打开封装
    void OpenFile(int flag)
    {
        _fd = ::open(gpipeFile.c_str(), flag);
        if (_fd < 0)
        {
            std::cerr << "openfile error" << std::endl;
            return;
        }
    }

public:
    Fifo()
        : _fd(-1)
    {
        umask(0);
        int n = mkfifo(gpipeFile.c_str(), gfifomode);
        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
            return;
        }
        std::cout << "mkfifo success" << std::endl;
    }
    ~Fifo()
    {
        if (_fd >= 0)
            ::close(_fd);
        int n = ::unlink(gpipeFile.c_str());
        if (n < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink success" << std::endl;
    }
    bool OpenForRead()
    {
        OpenFile(gforRead);
        if (_fd < 0)
            return false;
        return true;
    }
    bool OpenForWrite()
    {
        OpenFile(gforWrite);
        if (_fd < 0)
            return false;
        return true;
    }
    int Wait()
    {
        int code = 0;
        ssize_t n = ::read(_fd, &code, sizeof(code));
        if (n == sizeof(code))
        {
            return 0;
        }
        else if (n == 0)
        {
            return 1;
        }
        else
        {
            return 2;
        }
    }
    void Singal()
    {
        int code = 1;
        ::write(_fd, &code, sizeof(code));
    }

private:
    int _fd;
};

Fifo gpipe;